package cn.com.wangluotongxin.netty.rabbitmq;

import cn.com.wangluotongxin.admin.netty.AdminQueue;
import cn.com.wangluotongxin.admin.netty.pojo.MessageInfo;
import cn.com.wangluotongxin.admin.netty.pojo.NotifyResponse;
import cn.com.wangluotongxin.netty.cache.NettyChannelCacheUtil;
import cn.com.wangluotongxin.netty.pojo.ChannelPojo;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RabbitmqListener {

    // 单个发送一对一
    @RabbitListener(queues = AdminQueue.ADMIN_NETTY_MESSAGE_PUSH, ackMode = "AUTO")
    public void sendMessage(MessageInfo messageInfo) {
        if (messageInfo == null) return;
        log.info("收到netty发送消息:{}", JSONObject.toJSONString(messageInfo));
        ChannelPojo channelPojo = NettyChannelCacheUtil.get(messageInfo.getChannelId());
        if(channelPojo == null) return;
        Channel channel = channelPojo.getChannel();
        channel.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(messageInfo)));
    }

    @RabbitListener(queues = AdminQueue.ADMIN_NETTY_NOTIFY_RESPONSE, ackMode = "AUTO")
    public void notifyResponse(NotifyResponse response) {
        if(response == null) return;
        log.info("收到netty通知响应:{}", JSONObject.toJSONString(response));
        ChannelPojo channelPojo = NettyChannelCacheUtil.get(response.getChannelId());
        if(channelPojo == null) return;
        Channel channel = channelPojo.getChannel();
        channel.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(response)));
    }

    @RabbitListener(queues = AdminQueue.ADMIN_NETTY_AI_SEARCH_PUSH, ackMode = "AUTO")
    public void aiSearchPushQueue(MessageInfo messageInfo) {
        if (messageInfo == null) return;
        log.info("收到AI智能查询发送消息:{}", JSONObject.toJSONString(messageInfo));
        ChannelPojo channelPojo = NettyChannelCacheUtil.get(messageInfo.getChannelId());
        if(channelPojo == null) return;
        Channel channel = channelPojo.getChannel();
        channel.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(messageInfo)));
    }

    @RabbitListener(queues = AdminQueue.ADMIN_FRIEND_INPUT_STATUS_PUSH, ackMode = "AUTO")
    public void friendInputStatusPushQueue(MessageInfo messageInfo) {
        if (messageInfo == null) return;
        log.info("收到用户触发输入发送消息:{}", JSONObject.toJSONString(messageInfo));
        ChannelPojo channelPojo = NettyChannelCacheUtil.get(messageInfo.getChannelId());
        if(channelPojo == null) return;
        Channel channel = channelPojo.getChannel();
        channel.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(messageInfo)));
    }
}
